package com.qf.anli.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.anli.pojos.Student;
import com.qf.anli.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/stu")
public class StuController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/page/{currentPage}/{pageSize}")
    public IPage<Student> page(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        //健壮性判断
        if (currentPage==null || currentPage<=0){
            currentPage = 1;
        }
        if (pageSize==null || pageSize<=0){
            pageSize = 5;
        }

        //数据库的分页查询
        IPage<Student> page = new Page<>(currentPage,pageSize);
        //使用mybatisplus的分页插件，实现分页查询
        studentService.page(page);

        return page;
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Student stu){
        LambdaUpdateWrapper<Student> uw = new LambdaUpdateWrapper<>();
        //更新的条件
        uw.eq(Student::getNumber,stu.getNumber());
        //具体的更新内容直接通过stu对象传递
        return studentService.update(stu,uw);
    }

    @PostMapping("/add")
    public boolean add(@RequestBody Student stu){
        return studentService.save(stu);
    }

    @PostMapping("/del")
    public boolean del(String number){
        //根据number删除记录
        Wrapper<Student> qw = Wrappers.lambdaQuery(Student.class)
                .eq(Student::getNumber,number);

        return studentService.remove(qw);
    }
}
